﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.Text;
using System.Collections;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using System.Diagnostics;
using System.Device;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Text;

namespace unifiqAnthony
{
    public partial class ViewEventDetail : PhoneApplicationPage
    {
        WebClient client;
        private List<User> userList;
        private static string API_KEY = "AoetA0820tVc4COdo9bGyEKy0mBSDjoSeb9vlIRP3iC3RWibRFlwOGPGVLOUn7Fs";
        private RequestData requestData;
        private Event selectedEvent;
        private int userID;

        public ViewEventDetail()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            string url = "http://unifiq.5kportal.com/retrieve_all_users.php";
            Uri uri = new Uri(url);
            client = new WebClient();
            client.AllowReadStreamBuffering = true;

            client.DownloadStringCompleted += client_DownloadStringCompleted;
            client.DownloadProgressChanged += client_DownloadProgressChanged;

            client.DownloadStringAsync(uri);
        }

        private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Cancelled == false & e.Error == null)
            {
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(e.Result));
                ObservableCollection<User> list = new ObservableCollection<User>();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ObservableCollection<User>));
                list = (ObservableCollection<User>)serializer.ReadObject(ms);

                userList = new List<User>();

                foreach (User user in list)
                {
                    userList.Add(user);
                }

                set_event_detail();
            }

        }

        private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {

        }

        private void map_btn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ShowRoute.xaml?location=" + requestData.LocationDisplay + "&lat=" + requestData.latitude + "&lng=" + requestData.longitude, UriKind.Relative));
        }

        private void submit_suggestion_btn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/AddSuggestion.xaml?eventID=" + selectedEvent.id.ToString() + "&eventTitle=" + selectedEvent.name, UriKind.Relative));
        }

        private void view_suggestion_btn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ViewSuggestion.xaml?eventID=" + selectedEvent.id.ToString() + "&eventTitle=" + selectedEvent.name, UriKind.Relative));      
        }

        private void set_event_detail()
        {
            selectedEvent = (Event)PhoneApplicationService.Current.State["selectedEvent"];
            PageTitle.Text = selectedEvent.name;

            User user = (User)PhoneApplicationService.Current.State["currentUser"];
            userID = user.uid;

            int pos = 0;
            for (int i = 0; i < userList.Count; i++)
            {
                if (selectedEvent.creatorID == userList[i].uid)
                {
                    pos = i;
                    break;
                }
            }

            DisplayEvent displayEvent = new DisplayEvent(selectedEvent.id, userList[pos].name, selectedEvent.name, selectedEvent.dateTime, selectedEvent.groupID, "Loading location...", selectedEvent.description);
            selectedEvent_lb.Items.Add(displayEvent);

            if (selectedEvent.dateTime.Date.CompareTo(DateTime.Now.Date) >= 0 && userID != selectedEvent.creatorID)
            {
                submit_suggestion_btn.Visibility = Visibility.Visible;
            }

            string locationURL = "https://dev.virtualearth.net/REST/v1/Locations/" + selectedEvent.latitude.ToString() + "," + selectedEvent.longitude.ToString() + "?key=" + API_KEY;

            var autoCompleteClient = new RestClient(locationURL);
            var locationRequest = new RestRequest();
            locationRequest.Method = Method.GET;
            locationRequest.RequestFormat = DataFormat.Json;
            autoCompleteClient.ExecuteAsync(locationRequest, response =>
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var json = response.Content;
                    var jsonObject = JObject.Parse(json);
                    var dict = JsonConvert.DeserializeObject<RootObject>(json);
                    var resources = dict.resourceSets[0].resources;
                    foreach (var item in resources)
                    {
                        requestData = new RequestData();
                        requestData.addressString = item.address.formattedAddress.Split(',')[0];
                        requestData.state = item.address.adminDistrict;
                        requestData.city = item.address.adminDistrict2;
                        requestData.country = item.address.countryRegion;
                        requestData.latitude = item.geocodePoints[0].coordinates[0].ToString();
                        requestData.longitude = item.geocodePoints[0].coordinates[1].ToString();
                        requestData.LocationDisplay = item.address.formattedAddress.Split(',')[0];

                        if (!string.IsNullOrWhiteSpace(item.address.adminDistrict2))
                            requestData.LocationDisplay = requestData.LocationDisplay + ", " + item.address.adminDistrict2;
                        if (!string.IsNullOrWhiteSpace(item.address.adminDistrict))
                            requestData.LocationDisplay = requestData.LocationDisplay + ", " + item.address.adminDistrict;

                        displayEvent.location = requestData.LocationDisplay;
                        selectedEvent_lb.Items.RemoveAt(0);
                        selectedEvent_lb.Items.Add(displayEvent);
                    }
                }
            });
        }
    }

    public class DisplayEvent
    {
        public int id { get; set; }
        public string creator { get; set; }
        public string name { get; set; }
        public DateTime dateTime { get; set; }
        public int groupID { get; set; }
        public string location { get; set; }
        public string description { get; set; }

        public DisplayEvent(int id, string creator, string name, DateTime dateTime, int groupID, string location, string description)
        {
            this.id = id;
            this.creator = creator;
            this.name = name;
            this.dateTime = dateTime;
            this.groupID = groupID;
            this.location = location;
            this.description = description;
        }

    }

}